package frobagroup.config;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import frobagroup.BasePackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import java.util.Arrays;

/**
 * Created by Tinsley on 2016/7/12.
 */
@Configuration
@EnableMongoRepositories("frobagroup.repositories")
@PropertySource(value = { "file:/app/config/frobagroup.properties"})
@ComponentScan(basePackageClasses = BasePackage.class)
public class MongoConfig extends AbstractMongoConfiguration{

    @Autowired
    private Environment environment;

    @Override
    protected String getDatabaseName() {
        return "frobagroup";
    }

    @Bean
    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient("localhost");
    }

    @Bean
    public GridFsTemplate gridFsTemplate() throws Exception {
        return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
    }

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        //mongoDb for 1.9.2 暂时单节点
        int databasePort = Integer.parseInt(environment.getRequiredProperty("mongodb.databasePort"));
        String databaseName = environment.getRequiredProperty("mongodb.databaseName");
        String databaseAddress = environment.getRequiredProperty("mongodb.databaseAddress");
        String databaseUsername = environment.getRequiredProperty("mongodb.username");
        String databasePassword = environment.getRequiredProperty("mongodb.password");
        MongoCredential mongoCredential = MongoCredential.createCredential(databaseUsername, databaseName, databasePassword.toCharArray());
        MongoClient mongoClient= new MongoClient(new ServerAddress(databaseAddress,databasePort), Arrays.asList(mongoCredential));
        return new SimpleMongoDbFactory(mongoClient, databaseName);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }


}

